import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// 定义要暴露给渲染进程的 api 对象
const api = {
  ipcRenderer: {
    // 发送消息到主进程
    send: (channel: string, ...args: any[]) => ipcRenderer.send(channel, ...args),
    // 监听主进程发送的消息
    on: (channel: string, listener: (event: any, ...args: any[]) => void) =>
      ipcRenderer.on(channel, listener),
    // 移除监听器
    removeListener: (channel: string, listener: (event: any, ...args: any[]) => void) =>
      ipcRenderer.removeListener(channel, listener)
  }
}

if (process.contextIsolated) {
  try {
    // 暴露 electronAPI 到渲染进程
    contextBridge.exposeInMainWorld('electron', electronAPI)
    // 暴露自定义 api 到渲染进程
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
